// 
//  Copyright 2011  Joel Johnson
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
using System;
using System.Linq;
using System.Reflection;
using Servlets.Utils;
using Servlets.Attributes;
using System.Collections.Generic;

namespace Servlets.Api {
	public class TagManager {
		public static void DoTag(String className, String methodName, TagContext context, Dictionary<string, object> parameters) {
			Type type = Type.GetType(className);
			MethodInfo method = GetMethodWithTagAttribute(type, methodName);
			
			List<object> methodParams = new List<object>();
			methodParams.Add(context);
			ParameterInfo[] pinfo = method.GetParameters();
			for(int i = 0; i < pinfo.Length; i++) {
				methodParams.Add(parameters[pinfo[i].Name]);
			}

			object instance = null;
			if(!method.IsStatic) {
				instance = type.GetConstructor(new Type[]{}).Invoke(new Object[]{});
			}
			method.Invoke(instance, methodParams.ToArray());
		}
		
		/// <summary>
		/// Gets a method marked with TagAttribute that matches the given name.
		/// </summary>
		private static MethodInfo GetMethodWithTagAttribute(Type type, String name) {
			MethodInfo methodWithMethodName = null;
			foreach(MethodInfo method in type.GetMethods()) {
				object[] attributes = method.GetCustomAttributes(typeof(TagAttribute), false);
				if(attributes.Length > 0) {
					if((attributes[0] as TagAttribute).Name == name) {
						return method;
					}
				}
				if(method.Name == name) {
					//if there was a method with the name given, return it.
					//but only if there are no methods with a Tag.Name value == name
					methodWithMethodName = method;
				}
			}
			return methodWithMethodName; 
		}
	}
}
